<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="试卷名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="试卷名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="所属年级" prop="gradeInfoId">
          <el-select
            v-model="queryParams.gradeInfoId"
            clearable
            placeholder="所属年级"
            class="!w-[100px]"
          >
            <el-option
              v-for="option in optionsGrad"
              :key="option.id"
              :label="option.name"
              :value="option.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <i-ep-refresh />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button
          v-hasPerm="['exam:testpaperinfo:add']"
          type="success"
          @click="handleOpenDialog()"
        >
          <i-ep-plus />
          新增
        </el-button>
        <el-button
          v-hasPerm="['exam:testpaperinfo:delete']"
          type="danger"
          :disabled="removeIds.length === 0"
          @click="handleDelete()"
        >
          <i-ep-delete />
          删除
        </el-button>
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          key="name"
          label="试卷名称"
          prop="name"
          min-width="100"
        />
        <el-table-column
          key="gradeInfoName"
          label="年级"
          prop="gradeInfoName"
          min-width="100"
        />
        <el-table-column key="mark" label="总分" prop="mark" min-width="100" />
        <el-table-column
          key="questionNumber"
          label="试题数量"
          prop="questionNumber"
          min-width="100"
        />
        <el-table-column
          key="subjectName"
          label="科目"
          prop="subjectName"
          min-width="100"
        />
        <el-table-column
          key="examTime"
          label="考试时间"
          prop="examTime"
          min-width="100"
        >
          <template #default="scope">{{ scope.row.examTime }}分钟</template>
        </el-table-column>
        <el-table-column
          key="publishFlag"
          label="状态"
          prop="publishFlag"
          min-width="100"
        >
          <template #default="scope">
            <span v-if="scope.row.publishFlag === 0" style="color: #409eff">
              草稿
            </span>
            <span
              v-else-if="scope.row.publishFlag === 1"
              style="color: #67c23a"
            >
              已发布
            </span>
            <span v-else>未知状态</span>
          </template>
        </el-table-column>
        <el-table-column
          key="remark"
          label="备注"
          prop="remark"
          min-width="100"
        />
        <el-table-column
          key="createTime"
          label="创建时间"
          prop="createTime"
          min-width="100"
        />
        <el-table-column label="试题内容" min-width="100">
          <template #default="scope">
            <div class="question-content">
              <div class="content" v-dompurify-html="scope.row.content"></div>
            </div>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-dropdown>
              <a style="color: #409eff">
                操作
                <i><i-ep-arrow-down /></i>
              </a>

              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-if="scope.row.publishFlag === 0"
                    v-hasPerm="['exam:testpaperinfo:publish']"
                    type="primary"
                    size="small"
                    link
                    @click="publishTestPaperInfo(scope.row.id, 1)"
                  >
                    <i-ep-Promotion />
                    发布
                  </el-dropdown-item>

                  <!-- <el-dropdown-item
                    v-if="scope.row.publishFlag"
                    @click="goExamMonitor(scope.row)"
                  >
                    考试监控
                  </el-dropdown-item>-->

                  <el-dropdown-item @click="printPaper(scope.row)">
                    预览/打印
                  </el-dropdown-item>

                  <el-dropdown-item
                    v-if="scope.row.publishFlag === 1"
                    v-hasPerm="['exam:testpaperinfo:cancel']"
                    type="primary"
                    size="small"
                    link
                    @click="publishTestPaperInfo(scope.row.id, 0)"
                  >
                    <i-ep-bottom />
                    撤回
                  </el-dropdown-item>

                  <el-dropdown-item
                    v-hasPerm="['exam:testpaperinfo:relevanceQuestion']"
                    type="primary"
                    size="small"
                    link
                    @click="relevanceQuestion(scope.row)"
                  >
                    <i-ep-tickets />
                    试题管理
                  </el-dropdown-item>

                  <el-dropdown-item @click="openPaperSetting(scope.row)">
                    试卷设置
                  </el-dropdown-item>

                  <el-dropdown-item
                    v-if="scope.row.publishFlag === 0"
                    v-hasPerm="['exam:testpaperinfo:edit']"
                    type="primary"
                    size="small"
                    link
                    @click="handleOpenDialog(scope.row.id)"
                  >
                    <i-ep-edit />
                    修改
                  </el-dropdown-item>

                  <el-dropdown-item
                    v-if="scope.row.publishFlag === 0"
                    v-hasPerm="['exam:testpaperinfo:delete']"
                    type="danger"
                    size="small"
                    link
                    @click="handleDelete(scope.row.id)"
                  >
                    <i-ep-delete />
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.current"
        v-model:limit="queryParams.size"
        @pagination="handleQuery()"
      />
    </el-card>

    <!-- 试卷信息表表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="600px"
      @close="handleCloseDialog"
    >
      <el-form
        ref="dataFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="试卷名称" prop="name">
          <el-input v-model="formData.name" placeholder="试卷名称" />
        </el-form-item>
        <el-form-item label="考试时间" prop="examTime">
          <el-input-number
            v-model="formData.examTime"
            placeholder="考试时间(单位：分)"
            style="width: 50%"
          />
          <div class="input-group-append">分钟</div>
        </el-form-item>
        <el-form-item label="所属阶段:" prop="schoolType">
          <el-select
            v-model="formData.schoolType"
            clearable
            placeholder="所属阶段"
            class="!w-[200px]"
            @change="selectGradeType()"
          >
            <el-option
              v-for="option in options"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属年级:" prop="gradeInfoId">
          <el-select
            v-model="formData.gradeInfoId"
            clearable
            placeholder="所属年级"
            class="!w-[200px]"
            @change="selectSubjectType()"
          >
            <el-option
              v-for="option in optionsGrad"
              :key="option.id"
              :label="option.name"
              :value="option.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属科目:" prop="subjectId">
          <el-select
            v-model="formData.subjectId"
            clearable
            placeholder="所属科目"
            class="!w-[200px]"
          >
            <el-option
              v-for="option in optionsSub"
              :key="option.id"
              :label="option.name"
              :value="option.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="formData.sort"
            placeholder="排序"
            style="width: 30%"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            v-model="formData.remark"
            placeholder="备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确定</el-button>
          <el-button @click="handleCloseDialog">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!--试题管理的弹窗-->
    <el-dialog
      v-model="dialogRelevanceQuestion.visible"
      :title="dialogRelevanceQuestion.title"
      width="60%"
      @close="handleCloseDialogRelevanceQuestion"
    >
      <div class="search-container">
        <el-form
          ref="queryRelevanceFormRef"
          :model="queryRelevanceParams"
          :inline="true"
        >
          <el-form-item label="试题类型:" prop="questionType">
            <el-select
              v-model="queryRelevanceParams.questionType"
              clearable
              placeholder="试题类型"
              class="!w-[200px]"
            >
              <el-option
                v-for="option in optionsQuestion"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQueryRelevance">
              <i-ep-search />
              搜索
            </el-button>
            <el-button @click="handleResetQueryRelevance">
              <i-ep-refresh />
              重置
            </el-button>
            <el-button type="success" @click="handleImportRelevance">
              <i-ep-Upload />
              题库导入
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-card shadow="never" class="table-container">
        <el-table
          ref="dataRelevanceTableRef"
          v-loading="loading"
          :data="pageRelevanceData"
          highlight-current-row
          border
          @selection-change="handleSelectionChangeRelevance"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="试题内容" min-width="100">
            <template #default="scope">
              <div class="question-content">
                <div class="content" v-dompurify-html="scope.row.content"></div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="分数" prop="mark" min-width="100">
            <!-- key="mark"
            label="分数"
            prop="mark"
            min-width="100" -->
            <template #default="scope">
              <!-- 编辑 -->
              <el-input
                type="number"
                v-model="scope.row.mark"
                class="input"
                @blur="blurEvent(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="排序" prop="sort" min-width="100">
            <template #default="scope">
              <!-- 编辑 -->
              <el-input
                type="number"
                v-model="scope.row.sort"
                class="input"
                @blur="blurEvent(scope.row)"
              />
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-if="relevanceTotal > 0"
          v-model:total="relevanceTotal"
          v-model:page="queryParams.current"
          v-model:limit="queryParams.size"
          @pagination="handleQueryRelevance()"
        />
      </el-card>
    </el-dialog>

    <!--试题分页列表-->
    <el-dialog
      v-model="dialogQuestion.visible"
      :title="dialogQuestion.title"
      width="90%"
      height="80%"
      @close="handleCloseDialogQuestion"
    >
      <div class="search-container">
        <el-form
          ref="queryQuestionFormRef"
          :model="queryQuestionParams"
          :inline="true"
        >
          <el-form-item label="试题类型:" prop="questionType">
            <el-select
              v-model="queryQuestionParams.questionType"
              clearable
              placeholder="试题类型"
              class="!w-[200px]"
            >
              <el-option
                v-for="option in optionsQuestion"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="试题内容" prop="content">
            <el-input
              v-model="queryQuestionParams.content"
              placeholder="试题内容"
              clearable
              @keyup.enter="handleQuestionQuery()"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleQuestionQuery">
              <i-ep-search />
              搜索
            </el-button>
            <el-button @click="handleResetQuestionQuery">
              <i-ep-refresh />
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-card shadow="never" class="table-container">
        <el-table
          ref="dataQuestionTableRef"
          v-loading="loading"
          :data="pageQuestionData"
          highlight-current-row
          border
          @selection-change="handleSelectionQuestionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <!-- <el-table-column key="id" label="主键" prop="id" min-width="100" /> -->
          <el-table-column
            key="questionTypeName"
            label="试题类型"
            prop="questionTypeName"
            min-width="100"
          />
          <el-table-column label="试题内容" min-width="100">
            <template #default="scope">
              <div class="question-content">
                <div class="content" v-dompurify-html="scope.row.content"></div>
              </div>

              <!-- 选项区域 -->
              <div
                class="options-container"
                v-if="scope.row.options && scope.row.options.length"
              >
                <!-- 单选题 90 -->
                <template v-if="scope.row.type === '90'">
                  <el-radio-group v-model="scope.row.answer" disabled>
                    <div
                      v-for="option in scope.row.options"
                      :key="option.label"
                      class="option-item"
                    >
                      <el-radio :label="option.label">
                        <div class="option-label">
                          <span class="option-prefix">{{ option.label }}.</span>
                          <div
                            class="option-content"
                            v-dompurify-html="option.option_name"
                          ></div>
                        </div>
                      </el-radio>
                    </div>
                  </el-radio-group>
                </template>

                <!-- 多选题 91 -->
                <template v-else-if="scope.row.type === '91'">
                  <el-checkbox-group v-model="scope.row.answer" disabled>
                    <div
                      v-for="option in scope.row.options"
                      :key="option.label"
                      class="option-item"
                    >
                      <el-checkbox :label="option.label">
                        <div class="option-label">
                          <span class="option-prefix">{{ option.label }}.</span>
                          <div
                            class="option-content"
                            v-dompurify-html="option.option_name"
                          ></div>
                        </div>
                      </el-checkbox>
                    </div>
                  </el-checkbox-group>
                </template>
              </div>

              <!-- 判断题 95 -->
              <template v-if="scope.row.type === '95'">
                <div class="options-container">
                  <el-radio-group v-model="scope.row.answer" disabled>
                    <el-radio label="1">正确</el-radio>
                    <el-radio label="0">错误</el-radio>
                  </el-radio-group>
                </div>
              </template>

              <!-- 填空题 92、计算题 96、综合题 93、不定项 94 -->
              <template
                v-if="['92', '93', '94', '96'].includes(scope.row.type)"
              >
                <div class="answer-area">
                  <el-input
                    type="textarea"
                    v-model="scope.row.answer"
                    disabled
                    placeholder="答题区域"
                    rows="3"
                  />
                </div>
              </template>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="220">
            <template #default="scope">
              <el-button
                type="primary"
                size="small"
                link
                @click="handleQuestionPerview(scope.row.id)"
              >
                <i-ep-view />
                预览
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-if="total > 0"
          v-model:total="questionTotal"
          v-model:page="queryQuestionParams.current"
          v-model:limit="queryQuestionParams.size"
          @pagination="handleQuestionQuery()"
        />
      </el-card>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleQuestionSubmit">
            确定
          </el-button>
          <el-button @click="handleCloseDialogQuestion">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 试卷设置弹窗 -->
    <el-dialog
      v-model="dialogPaperSetting.visible"
      :title="dialogPaperSetting.title"
      width="700px"
      @close="handleClosePaperSetting"
    >
      <el-tabs v-model="activeName">
        <!-- 考试限制 tab -->
        <el-tab-pane label="考试限制" name="exam">
          <el-form :model="paperSettingForm" label-width="120px">
            <el-form-item label="有效期:">
              <el-select v-model="paperSettingForm.examType" class="!w-[200px]">
                <el-option label="指定开放时间" :value="1" />
                <el-option label="永久有效" :value="2" />
              </el-select>
            </el-form-item>

            <el-form-item
              v-show="paperSettingForm.examType === 1"
              label="开放时间:"
            >
              <div class="date-picker-container">
                <el-date-picker
                  v-model="paperSettingForm.startTime"
                  type="datetime"
                  placeholder="���始日期"
                  class="date-picker"
                />
                <span class="date-separator">至</span>
                <el-date-picker
                  v-model="paperSettingForm.endTime"
                  type="datetime"
                  placeholder="结束日期"
                  class="date-picker"
                />
              </div>
            </el-form-item>

            <el-form-item label="答卷次数:">
              <div class="answer-times-container">
                <el-select
                  v-model="paperSettingForm.referenceNumber"
                  class="!w-[200px]"
                  @change="handleAnswerTimesChange"
                >
                  <el-option label="1次" :value="1" />
                  <el-option label="不限次数" :value="-1" />
                  <el-option label="自定义" :value="2" />
                </el-select>
                <el-input-number
                  v-if="paperSettingForm.referenceNumber === 2"
                  v-model="paperSettingForm.referenceNumber"
                  :min="1"
                  class="custom-times"
                  placeholder="请输入次数"
                />
                <span v-if="paperSettingForm.referenceNumber === 2">次</span>
              </div>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 结果设置 tab -->
        <el-tab-pane label="结果设置" name="result">
          <el-form :model="paperSettingForm" label-width="120px">
            <el-form-item label="提交答卷:">
              <el-radio-group
                v-model="paperSettingForm.commitAfterType"
                @change="handleShowResultChange"
              >
                <el-radio :label="1">显示成绩</el-radio>
                <el-radio :label="0">不显示成绩</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="显示名次:">
              <el-switch
                :model-value="paperSettingForm.showMarkSort === 1"
                @update:model-value="
                  (val) => (paperSettingForm.showMarkSort = val ? 1 : 0)
                "
              />
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handlePaperSettingSubmit">
            确定
          </el-button>
          <el-button @click="handleClosePaperSetting">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 预览弹窗 -->
    <el-dialog
      v-model="dialogPreview.visible"
      :title="dialogPreview.title"
      width="80%"
      @close="handleClosePreviewDialog"
    >
      <div v-loading="loading">
        <div
          v-for="(question, index) in previewQuestions"
          :key="index"
          class="question-item"
        >
          <!-- 题目内容 -->
          <div class="question-content">
            <div class="content" v-dompurify-html="question.content"></div>
          </div>

          <!-- 选项区域 -->
          <div
            class="options-container"
            v-if="question.options && question.options.length"
          >
            <!-- 单选题 90 -->
            <template v-if="question.type === '90'">
              <el-radio-group v-model="question.answer" disabled>
                <div
                  v-for="option in question.options"
                  :key="option.label"
                  class="option-item"
                >
                  <el-radio :label="option.label">
                    <div class="option-label">
                      <span class="option-prefix">{{ option.label }}.</span>
                      <div
                        class="option-content"
                        v-dompurify-html="option.option_name"
                      ></div>
                    </div>
                  </el-radio>
                </div>
              </el-radio-group>
            </template>

            <!-- 多选题 91 -->
            <template v-else-if="question.type === '91'">
              <el-checkbox-group v-model="question.answer" disabled>
                <div
                  v-for="option in question.options"
                  :key="option.label"
                  class="option-item"
                >
                  <el-checkbox :label="option.label">
                    <div class="option-label">
                      <span class="option-prefix">{{ option.label }}.</span>
                      <div
                        class="option-content"
                        v-dompurify-html="option.option_name"
                      ></div>
                    </div>
                  </el-checkbox>
                </div>
              </el-checkbox-group>
            </template>
          </div>

          <!-- 判断题 95 -->
          <template v-if="question.type === '95'">
            <div class="options-container">
              <el-radio-group v-model="question.answer" disabled>
                <el-radio label="1">正确</el-radio>
                <el-radio label="0">错误</el-radio>
              </el-radio-group>
            </div>
          </template>

          <!-- 填空题 92、计算题 96、综合题 93、不定项 94 -->
          <template v-if="['92', '93', '94', '96'].includes(question.type)">
            <div class="answer-area">
              <el-input
                type="textarea"
                v-model="question.answer"
                disabled
                placeholder="答题区域"
                rows="3"
              />
            </div>
          </template>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClosePreviewDialog">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "TestPaperInfo",
  inheritAttrs: false,
});

import TestPaperInfoAPI, {
  TestPaperInfoForm,
  TestPaperInfoPageQuery,
  TestPaperInfoPageVO,
} from "@/api/test_paper_info";
import GradeInfoAPI, { GradeInfoPageVO } from "@/api/grade_info";
import DictAPI from "@/api/dict";
import SubjectInfoAPI, { SubjectInfoPageVO } from "@/api/subject_info";
import TestPaperQuestionInfoAPI, {
  TestPaperQuestionInfoPageQuery,
  TestPaperQuestionInfoPageVO,
  TestPaperQuestionInfoForm,
} from "@/api/test_paper_question_info";
import QuestionInfoAPI, {
  QuestionInfoPageQuery,
  QuestionInfoPageVO,
} from "@/api/question_info";
import TestPaperInfoSettingAPI, {
  TestPaperInfoSettingForm,
} from "@/api/test_paper_info_setting";

const queryFormRef = ref<ElForm>();
const dataFormRef = ref<ElForm>();
const queryQuestionFormRef = ref<ElForm>();
const queryRelevanceFormRef = ref<ElForm>();
const dataRelevanceTableRef = ref<ElForm>();
const dataQuestionTableRef = ref<ElForm>();

const loading = ref(false);
const removeIds = ref<number[]>([]);
const relevanceRemoveIds = ref<number[]>([]);
const testPaperInfoIds = ref<number[]>([]);
const total = ref(0);
const relevanceTotal = ref(0);
const questionTotal = ref(0);
const optionsQuestion: Ref<OptionType[]> = ref([]);

const queryParams = reactive<TestPaperInfoPageQuery>({
  current: 1,
  size: 10,
});

const queryRelevanceParams = reactive<TestPaperQuestionInfoPageQuery>({
  current: 1,
  size: 10,
});

const queryQuestionParams = reactive<QuestionInfoPageQuery>({
  current: 1,
  size: 10,
});

// 试卷信息表表格数据
const pageData = ref<TestPaperInfoPageVO[]>([]);
const pageRelevanceData = ref<TestPaperQuestionInfoPageVO[]>([]);
const optionsGrad: Ref<GradeInfoPageVO[]> = ref([]);
const options: Ref<OptionType[]> = ref([]);
const optionsSub: Ref<SubjectInfoPageVO[]> = ref([]);
const pageQuestionData = ref<QuestionInfoPageVO[]>([]);
const testPaperQuestionInfoForm: Ref<TestPaperQuestionInfoForm[]> = ref([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 弹窗
const dialogRelevanceQuestion = reactive({
  title: "",
  visible: false,
});

// 弹窗
const dialogQuestion = reactive({
  title: "",
  visible: false,
});

// 试卷信息表表单数据
const formData = reactive<TestPaperInfoForm>({});

// 试卷信息表表单校验规则
const rules = reactive({});

// 试卷设置弹窗
const dialogPaperSetting = reactive({
  title: "试卷设置",
  visible: false,
});

// 试卷设置表单数据
const paperSettingForm = reactive<TestPaperInfoSettingForm>({
  id: undefined,
  testPaperInfoId: undefined,
  examType: 2,
  startTime: "",
  endTime: "",
  referenceNumber: 1,
  commitAfterType: 1,
  showMarkSort: 0,
  showStudentSort: 0,
});

const activeName = ref("exam"); // 当前激活的 tab 页签

/** 查询试卷信息表 */
function handleQuery() {
  loading.value = true;
  TestPaperInfoAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置试卷信息表查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.current = 1;
  handleQuery();
}

/** 行选框选记录中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 打开试卷信息表弹窗 */
function handleOpenDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改试卷信息表";
    TestPaperInfoAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增试卷信息表";
  }
}

/** 提交试卷信息表表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        TestPaperInfoAPI.update(formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        TestPaperInfoAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭试卷信息表弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 删除试卷信息表 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      TestPaperInfoAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("取消删除");
    }
  );
}

function selectGradeType() {
  queryParams.schoolType = formData.schoolType;
  // 根据字典id获年级管理列表
  GradeInfoAPI.getList(queryParams).then((data) => {
    optionsGrad.value = data;
  });
}

function selectSubjectType() {
  queryParams.gradeInfoId = formData.gradeInfoId;
  SubjectInfoAPI.getList(queryParams).then((data) => {
    optionsSub.value = data;
  });
}

//发布试题
function publishTestPaperInfo(id: number, status: number) {
  const updateData = {
    id: 0,
    publishFlag: 0,
  };
  updateData.id = id;
  updateData.publishFlag = status;
  TestPaperInfoAPI.update(updateData).then(() => {
    ElMessage.success("操作成功");
    handleResetQuery();
  });
}

function relevanceQuestion(row: any) {
  dialogRelevanceQuestion.visible = true;
  dialogRelevanceQuestion.title = "试题管理";
  queryQuestionParams.subjectId = row.subjectId;
  queryQuestionParams.gradeInfoId = row.gradeInfoId;
  queryParams.subjectId = row.subjectId;
  queryParams.gradeInfoId = row.gradeInfoId;
  testPaperInfoIds.value = row.id;
  // 根据字典编码获取字典项
  DictAPI.getOptions("STLX").then((data) => {
    optionsQuestion.value = data;
  });

  handleQueryRelevance();
}

function handleCloseDialogRelevanceQuestion() {
  dialogRelevanceQuestion.visible = false;
}

function handleQueryRelevance() {
  loading.value = true;
  TestPaperQuestionInfoAPI.getPage(queryParams)
    .then((data) => {
      pageRelevanceData.value = data.list;
      relevanceTotal.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

function handleResetQueryRelevance() {
  queryRelevanceFormRef.value.resetFields();
  queryRelevanceFormRef.value.clearValidate();
}

function handleSelectionChangeRelevance(selection: any) {
  relevanceRemoveIds.value = selection.map((item: any) => item.id);
}

function handleCloseDialogQuestion() {
  dialogQuestion.visible = false;
}

//试题导入
function handleImportRelevance(row: any) {
  dialogQuestion.visible = true;
  dialogQuestion.title = "题库导入";
  handleQuestionQuery();
}

function handleResetQuestionQuery() {
  queryQuestionFormRef.value.resetFields();
  queryQuestionFormRef.value.clearValidate();
}

function handleQuestionQuery() {
  loading.value = true;
  queryQuestionParams.bs = "t";
  QuestionInfoAPI.getPage(queryQuestionParams)
    .then((data) => {
      pageQuestionData.value = data.list;
      questionTotal.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

function handleSelectionQuestionChange(selection: any) {
  // questionIds.value = selection.map((item: any) => item.id);
  testPaperQuestionInfoForm.value = selection.map((item: any) => ({
    testPaperInfoId: testPaperInfoIds.value,
    questionInfoId: item.id,
  }));
}

function handleQuestionSubmit() {
  TestPaperQuestionInfoAPI.add(testPaperQuestionInfoForm.value).then(() => {
    ElMessage.success("操作成功");
    dialogQuestion.visible = false;
    handleQueryRelevance();
  });
}

// 预览弹窗数据
const previewQuestions = ref<any[]>([]);

function handleQuestionPerview(questionId: number) {
  loading.value = true;
  // 获取试题详情
  QuestionInfoAPI.getFormData(questionId)
    .then((res) => {
      const data = res;
      // 根据试题类型处理数据
      const questionData = {
        type: data.questionType.toString(), // 转换为字符串以匹配模板中的判断
        content: data.content,
        options: data.options ? JSON.parse(data.options) : [], // 解析选项JSON
        answer: "", // 预览时不显示答案
      };

      // 更新预览数据
      previewQuestions.value = [questionData];

      // 显示弹窗
      dialogPreview.visible = true;
    })
    .catch((error) => {
      ElMessage.error("获取试题详情失败");
      console.error(error);
    })
    .finally(() => {
      loading.value = false;
    });
}

function blurEvent(row: any) {
  TestPaperQuestionInfoAPI.update(row).then(() => {
    // ElMessage.success("操作成功");
    // handleQueryRelevance();
  });
}

// 打开试卷设置弹窗
function openPaperSetting(row: any) {
  dialogPaperSetting.visible = true;
  // 获取试卷设置数据
  TestPaperInfoSettingAPI.getFormData(row.id).then((data) => {
    // 确保所有字段都有默认值
    const defaultData = {
      validTimeType: 2,
      answerTimesType: 1,
      answerTimes: 1,
      showResultFlag: 1,
      showRankFlag: 0,
      testPaperInfoId: row.id,
      ...data, // 使用后端返回的数据覆盖默认值
    };
    Object.assign(paperSettingForm, defaultData);
  });
}

// 关闭试卷设置弹窗
function handleClosePaperSetting() {
  dialogPaperSetting.visible = false;
  // 重置表单为默认值
  Object.assign(paperSettingForm, {
    id: undefined,
    examType: 2,
    startTime: "",
    endTime: "",
    referenceNumber: 1,
    commitAfterType: 1,
    showMarkSort: 0,
    showStudentSort: 0,
  });
}

// 提交试卷设置
function handlePaperSettingSubmit() {
  if (paperSettingForm.id) {
    // 更新
    TestPaperInfoSettingAPI.update(paperSettingForm).then(() => {
      ElMessage.success("设置成功");
      handleClosePaperSetting();
      handleQuery();
    });
  } else {
    // 新增
    TestPaperInfoSettingAPI.add(paperSettingForm).then(() => {
      ElMessage.success("设置成功");
      handleClosePaperSetting();
      handleQuery();
    });
  }
}

// 处理答卷次数变化
function handleAnswerTimesChange(value: number) {
  if (value === 1) {
    paperSettingForm.referenceNumber = 1;
  } else if (value === -1) {
    paperSettingForm.referenceNumber = -1;
  } else if (value === 2) {
    // 选择自定义时，不要��置 referenceNumber
    // 让用户以通过 el-input-number 输入自定义值
    return;
  }
}

// 处理显示成绩变化
function handleShowResultChange(value: number) {
  if (value === 0) {
    // 如果选择不显示成绩，则自动关闭显示名次
    paperSettingForm.showMarkSort = 0;
    paperSettingForm.showStudentSort = 0;
  }
}

// 预览弹窗
const dialogPreview = reactive({
  title: "试卷预览",
  visible: false,
});

// 关闭预览弹窗
function handleClosePreviewDialog() {
  dialogPreview.visible = false;
}

function printPaper(row: any) {
  TestPaperInfoAPI.getPrintUrl(row.id, { responseType: "blob" })
    .then((response) => {
      // 创建 blob 对象
      const blob = new Blob([response.data], { type: "application/pdf" });

      // 创建临时 URL
      const fileURL = URL.createObjectURL(blob);

      // 创建一个隐藏的 <a> 标签用于下载
      const link = document.createElement("a");
      link.href = fileURL;
      link.target = "_blank";

      // 如果要下载文件，可以设置 download 属性
      // link.download = `试卷预览_${row.name}.pdf`;

      // 模拟点击打开新窗口预览
      link.click();

      // 清理临时 URL
      setTimeout(() => {
        URL.revokeObjectURL(fileURL);
      }, 100);
    })
    .catch((error) => {
      ElMessage.error("预览失败");
      console.error(error);
    });
}

onMounted(() => {
  // 根据字典编码获取字典项
  DictAPI.getOptions("SSJD").then((data) => {
    options.value = data;
  });

  selectGradeType();
  handleQuery();
});
</script>
<style scoped>
.input-group-append {
  display: flex;
  align-items: center;
  padding: 0 10px;
  margin: 1px;
  background-color: #f5f7fa;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.date-picker-container {
  display: flex;
  gap: 12px;
  align-items: center;
}

.date-picker {
  width: 180px;
}

.date-separator {
  flex-shrink: 0;
  color: #606266;
}

.answer-times-container {
  display: flex;
  gap: 12px;
  align-items: center;
}

.custom-times {
  width: 120px;
}

.question-item {
  padding: 20px;
  margin-bottom: 30px;
  background-color: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.question-content {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20px;
  font-size: 15px;
}

.question-index {
  flex-shrink: 0;
  margin-right: 4px;
  font-weight: bold;
}

.content {
  flex: 1;
}

.options-container {
  padding-left: 25px;
}

.option-item {
  margin: 6px 0;
}

/* 统一所有选项的基础样式 */
.option-item :deep(.el-radio),
.option-item :deep(.el-checkbox) {
  display: flex !important;
  align-items: flex-start;
  width: 100%;
  height: auto;
  padding: 0;
  margin-right: 0;
}

/* 统一单选和多选的基础样式 */
.option-item :deep(.el-radio__input),
.option-item :deep(.el-checkbox__input) {
  margin-top: 2px;
}

/* 统一标签容器的样式 */
.option-item :deep(.el-radio__label),
.option-item :deep(.el-checkbox__label) {
  width: calc(100% - 24px);
  padding-left: 6px;
  line-height: 1.4;
  white-space: normal;
}

/* 统一选项标签布局 */
.option-label {
  display: flex;
  align-items: flex-start;
  width: 100%;
  min-height: 20px;
}

/* 统一选项前缀样式 */
.option-prefix {
  flex-shrink: 0;
  min-width: 12px;
  margin-right: 2px;
  font-weight: normal;
}

/* 统一选项内容区域样式 */
.option-content {
  flex: 1;
  padding-top: 0;
  margin-left: -1px;
  line-height: 1.4;
}

/* 选项内容中的段落样式 */
.option-content :deep(p) {
  margin: 0;
  line-height: 1.5;
}

/* 选项内容中的图片样式 */
.option-content :deep(img) {
  max-width: 100%;
  height: auto;
  margin: 4px 0;
  vertical-align: middle;
}

/* 选项内容中的公式样式 */
.option-content :deep(.katex) {
  display: inline-block;
  vertical-align: middle;
}

.answer-area {
  padding-left: 25px;
  margin-top: 15px;
}

.dialog-footer {
  text-align: right;
}
</style>
